package com.skywalker.common.plugin.j2cache;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;


/**
 * @user: skywalker
 * @date: 2019/4/13 21:27
 * @description: 借鉴com.jfinal.plugin.ehcache.EvictInterceptor，
 * 配合String[]数组类型的CacheName以及J2CacheKit一起使用
 */
public class EvictInterceptor implements Interceptor {

    public void intercept(Invocation inv) {
        inv.invoke();

        String[] cacheNames = getCacheName(inv);
        if (cacheNames.length == 1) {
            J2CacheKit.removeAll(cacheNames[0].trim());
        } else {
            for (String cn : cacheNames) {
                J2CacheKit.removeAll(cn.trim());
            }
        }
    }

    /**
     * 获取 @CacheName 注解配置的 cacheName，注解可配置在方法和类之上
     */
    protected String[] getCacheName(Invocation inv) {
        CacheName cacheName = inv.getMethod().getAnnotation(CacheName.class);
        if (cacheName != null) {
            return cacheName.value();
        }

        cacheName = inv.getController().getClass().getAnnotation(CacheName.class);
        if (cacheName == null) {
            throw new RuntimeException("EvictInterceptor need CacheName annotation in controller.");
        }
        return cacheName.value();
    }
}
